package ru.aslanov.schedule.server.services;

import ru.aslanov.schedule.model.DataItem;
import ru.aslanov.schedule.model.Operation;
import ru.aslanov.schedule.model.User;
import ru.aslanov.schedule.server.AccessDeniedException;
import ru.aslanov.schedule.server.AccessManager;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 19, 2010 12:08:05 PM
 *
 * @author Sergey Aslanov
 */
public class UserService extends ScheduleChildService<User> {

    public UserService() {
        super("email");
    }

    @Override
    protected void fillDataItem(DataItem dataItem, User object, HttpServletRequest request, PersistenceManager pm) throws Exception {
        super.fillDataItem(dataItem, object, request, pm);
        setAttr(dataItem, "email", object.getEmail());
        setAttr(dataItem, "isAdmin", object.isAdmin());
    }

    @Override
    protected void makeObjectPersistent(PersistenceManager pm, User object, HttpServletRequest request) {
        getParent(pm, request).getUsers().add(object);
    }

    @Override
    protected Class<User> getEntityClass() {        
        return User.class;
    }

    @Override
    protected boolean checkPermission(User existingEntity, HttpServletRequest request, PersistenceManager pm, Operation operation) throws AccessDeniedException {
        String scheduleKey = existingEntity != null ? existingEntity.getSchedule().getEncodedKey() : getParentKey(request);
        return AccessManager.getInstance().isScheduleAdmin(scheduleKey);
    }

    @Override
    protected void checkParentViewAccess(String parentKey, HttpServletRequest request) throws AccessDeniedException {
        if (!AccessManager.getInstance().isScheduleAdmin(parentKey)) {
            throw new AccessDeniedException(request);
        }
    }
}
